package com.zzyang.cloud.lb;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义轮询算法
 *
 * @author zhuoziyang
 * @date 2020/10/25 17:30
 */
@Component
public class MyRoundLoadBalance implements MyLoadBalance {

    @Autowired
    private DiscoveryClient discoveryClient;

    private final String SERVICE_NAME = "CLOUD-PAYMENT-SERVICE";

    private final AtomicInteger current = new AtomicInteger(0);

    public ServiceInstance choose() {

        List<ServiceInstance> clientInstances = discoveryClient.getInstances(SERVICE_NAME);

        int nextIndex = getNextIndex();
        int size = clientInstances.size();

        int next = nextIndex % size;

        return clientInstances.get(next);
    }

    private final int getNextIndex() {
        int currentIndex, nextIndex;
        do {
            currentIndex = current.get();
            nextIndex = currentIndex >= Integer.MAX_VALUE ? 0 : currentIndex + 1;
        } while (!current.compareAndSet(currentIndex, nextIndex));

        return nextIndex;
    }

}
